<?php
/**
 * Created by PhpStorm.
 * User: MSQ
 * Date: 2021/9/27
 * Time: 16:54
 */

namespace App\Handler\WebSocket;


use App\Model\Baiyou\ApiAccessToken;
use App\Service\Baiyou\PatientInfusionQueueService;
use App\Utils\Common;
use App\Utils\LogHelp;
use App\Utils\RedisHelp;
use App\Utils\WebSocketMessage;
use EasySwoole\EasySwoole\Config;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class ScreenAuthHandler extends BaseHandler
{
    /**
     * 白友大屏登录 {"msgType":"screenAuth","checkType":2,"content":{"projectId":1,"account":"admin","password":"jgwl123456","token":""}}
     * @return string
     */
    public function handler(): string
    {
        $token = $this->content['token'] ?? '';
        if ($token) {
            $data = Common::decodeToken($token);
            if ($data === false) {
                $data = WebSocketMessage::getMessage(WebSocketMessage::ErrorAuth, "无效token");
                return $data;
            }

            $projectId = intval($data['project_id'] ?? 0);
            $account = $data['account'] ?? '';
            $password = $data['password'] ?? '';
        } else {
            $projectId = $this->content['projectId'] ?? 0;
            $account = $this->content['account'] ?? '';
            $password = $this->content['password'] ?? '';
        }
        if (empty($projectId)) {
            $data = WebSocketMessage::getErrorMessage("项目ID不能为空");
            return $data;
        }
        $projectAccount = Common::getProjectAccount($projectId);
        if (empty($projectAccount)) {
            $data = WebSocketMessage::getErrorMessage("项目未配置，无法登陆");
            return $data;
        }
        if ($projectAccount['account'] != $account || $projectAccount['password'] != $password) {
            $data = WebSocketMessage::getErrorMessage("账号or密码错误");
            return $data;
        }

        if (empty($token)) {
            $token = Common::encodeToken($projectId, $account, $password);
        }

        $redisHelp = new RedisHelp();
        // 项目fd集合
        $redisHelp->setScreenProjectFd($projectId, $this->fd);
        // fd信息
        $redisHelp->setScreenFd($this->fd, [
            'project_id' => $projectId,
            'check_type' => WebSocketMessage::CheckTypeScreen,
        ]);

        // 异步推送大屏列表
        $service = new PatientInfusionQueueService();
        $service->sendScreenNoticeList($projectId);

        $data = WebSocketMessage::getMessage(WebSocketMessage::ScreenAuthRes, ['token' => $token]);
        return $data;
    }
}
